import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author by zyl
 * @date 2020/3/28.
 */
public class SocketUtils {
    public static String in(int port){
        String res="";
        ServerSocket server;
        Socket socket;
        InputStream inputStream;
        try {
            server = new ServerSocket(port);
            socket=server.accept();
            inputStream=socket.getInputStream();
            byte []bytes=new byte[2048];
            int len;
            StringBuilder sb=new StringBuilder();
            while((len=inputStream.read(bytes))!=-1){
                sb.append(new String(bytes,0,len,"UTF-8"));
                if(len>1)
                    break;
            }
            inputStream.close();
            socket.close();
            server.close();
            res=sb.toString();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return res;
    }

    public static void out(String ip,int port,String msg){
        try {
            Socket socket = new Socket(ip, port);
            OutputStream outputStream = socket.getOutputStream();
            socket.getOutputStream().write(msg.getBytes("UTF-8"));
            outputStream.close();
            socket.close();
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}